package org.ace.logic.user;

import javax.annotation.Resource;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;

import org.ace.biz.user.IPlayerBiz;
import org.ace.endingCode.SocketModel;
import org.ace.protocol.Protocol;
import org.apache.log4j.Logger;

public abstract class AbstractUserHandlerImpl {
	
	public Logger logger=Logger.getLogger(getClass());
	
	@Resource(name="playerBiz")
	public IPlayerBiz playerBiz;
	private int area;
	
	public int getArea() {
		return area;
	}
	public void setArea(int area) {
		this.area = area;
	}

	/*
	 * type模块不用改变，所有userhandlerimpl继承这个抽象类，直接用
	 * */
	public  int getType()
	{
		return Protocol.TYPE_USER;
	}
	
	
	
	public Integer getUserId(Channel channel){
		return playerBiz.getUserId(channel);
	}

	@SuppressWarnings("rawtypes")
	public void messageReceived(Channel channel, SocketModel message) {
		process(channel, message);
	}

	@SuppressWarnings("rawtypes")
	protected abstract void process(Channel channel, SocketModel message);

	public void write(Integer userId,int optionid,Object message){
		Channel channel= playerBiz.getChannel(userId);
		if(channel!=null)
		//logger.debug("write type    "+getType()+"    area    "+getArea()+"    command    "+command+"    message    "+message);
			write(channel,optionid , message);
	}
	
	/*
	 * 发送已 序列化的消息 buff
	 * */
	public void write (Integer userId,ByteBuf buff)
	{
		Channel channel = playerBiz.getChannel(userId);
		if(channel!= null)
		{
			write(channel,buff);
		}
	}
	
	public void write(Channel channel,ByteBuf buff)
	{
		channel.writeAndFlush(buff.copy());
	}
	/**
	 * 发送消息给用户
	 * 
	 * @param channel
	 *            用户channel
	 * @param command
	 *            协议
	 * @param message
	 *            消息体
	 */
	public void write(Channel channel,int optionId , Object message) {
		logger.debug("write optionId   "+optionId + "    message    " + message);
		channel.writeAndFlush(createSocketModel(optionId, message));
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public SocketModel createSocketModel(int optionId,Object message) {
		SocketModel sm = new SocketModel();
		sm.setOpDefinde(optionId);
		sm.setMessage(message);
		return sm;
	}
	
	protected void onShake(Channel channel){
		//默认不做任何事情---有操作 自己实现克
	}
}
